package cn.tedu.boot.ers.controller.handler;

import cn.tedu.boot.ers.exception.ServiceException;
import cn.tedu.boot.ers.web.State;
import cn.tedu.boot.ers.web.JsonResult;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handleServiceException(ServiceException e) {
       return JsonResult.fail(e.getState(), e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public JsonResult<Void> handleBindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String defaultMessage = bindingResult.getFieldError().getDefaultMessage();
        return JsonResult.fail(State.ERR_BAD_REQUEST,defaultMessage);
    }

}
